package com.learn.controller;


import com.learn.common.Response;
import com.learn.entity.User;
import com.learn.entity.UserExample;
import com.learn.mybatis.mapper.UserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/api")
public class LoginController {

    HashMap<String, String> Session_username = new HashMap<>();

    @Autowired
    UserMapper userMapper;

    @PostMapping("/login")
    public Response<Object> login(@RequestBody User user, HttpServletResponse response) {
//        UserExample userExample = new UserExample();
//        UserExample.Criteria criteria = userExample.createCriteria();
//        criteria.andUsernameEqualTo(user.getUsername());
//        List<User> users = userMapper.selectByExample(userExample);
////        用户名不存在
//        if (users.get(0) == null) {
//            return Response.error("用户名密码错误");
//        }
//        if (!users.get(0).getPassword().equals(user.getPassword())) {
//            return Response.error("用户名密码错误");
//        }
//        Cookie userId = new Cookie("userId", String.valueOf(users.get(0).getId()));
//        userId.setMaxAge(60 * 60 * 60);
//        userId.setPath("/");
//        response.addCookie(userId);
//        return Response.success(users.get(0));

//        subject => securitymanager => realm


//        使用shiro对登录验证进行改造
//        获取用户
        Subject subject = SecurityUtils.getSubject();
//        获取令牌
        AuthenticationToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        try {
            Session_username.put("JSESSIONID", user.getUsername());
            subject.login(token);
            return Response.success("登录成功");
        } catch (UnknownAccountException | IncorrectCredentialsException e) {
            return Response.error("用户名密码错误");
        } //            密码错误

    }

    @PostMapping("/logout")
    public Response<String> logout(HttpServletResponse response) {
//        Cookie killMyCookie = new Cookie("userId", null);
//        killMyCookie.setMaxAge(0);
//        killMyCookie.setPath("/");
//        response.addCookie(killMyCookie);
//        使用shiro改造退出功能
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout();
        }
        return Response.success("退出登录成功");
    }

    @RequiresAuthentication
    @GetMapping("/me")
    public Response<String> isLogin(HttpServletRequest request) {
        for (Cookie cookie : request.getCookies()) {
            System.out.println(cookie.getName());
            if (cookie.getName().equals("JSESSIONID")) {
                return Response.of(Session_username.get("JSESSIONID"));
            }
        }
        return Response.error("用户未登录");
    }
}
